import Reflux from 'reflux';
import PageConst from './PageConst';
import Actions from './Actions';
import update from 'react-addons-update';
import nattyStorage from 'natty-storage';
import DB from '../../../app/db';
import {Control} from 'react-keeper';

export default Reflux.createStore({
  listenables: [Actions],
  data: {
    ...PageConst,
    tab: 1,
    suggestList: [],
    pageIndex: 1, //当前页,从0开始
  },

  onChangeTab: function (props) {
    var that = this;
    that.data.tab = update(that.data.tab, {$set: props});
    that.updateComponent();
    that.onLoadData();
  },

  onLoadData: function () {
    let that = this;

    that.data = update(that.data, {
      suggestList: {$set: []}
    });

    DB.WechatAPI.loadSuggestionList({
      page: 1,
      creatorId: '',
      suggesttype: that.data.tab ?  that.data.tab : 1
    }).then(
      function (content) {

        that.data = update(that.data, {
          suggestList: {$push: content.content},
          pageIndex: {
            $apply: function (x) {
              return x + 1;
            }
          }
        });
        that.updateComponent();
      },
      function (error) {
        console.log(error);
      }
    );
  },

  onLoadMore: function (resolve, finish) {

    let that = this;



    that.data = update(that.data, {
      tab: {$set:  that.data.tab ? that.data.tab : 1 }
    });

    that.updateComponent();

    DB.WechatAPI.loadSuggestionList({
      page: that.data.pageIndex,
      type: that.data.tab
    }).then(
      function (content) {
        if (content.content.length > 0) {
          that.data = update(that.data, {
            suggestList: {$push: content.content},
            pageIndex: {
              $apply: function (x) {
                return x + 1;
              }
            }
          });
          that.updateComponent();
          resolve();
        } else {
          finish();
        }
      },
      function (error) {
        finish();
        console.log(error);
      }
    );
  },


  updateComponent: function () {
    this.trigger(this.data);
  },

  getInitialState: function () {
    return this.data;
  }
});
